package com.ygq.controller;


import DTO.SubmitStudentScoreDTO;
import VO.UserMsgVO;
import VO.WorkMsgVO;
import VO.WorkScoreVO;
import VO.WorksVO;
import com.ygq.GradesService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import result.Result;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/teacher/grades")
@Slf4j
public class GradesController {
    @Autowired
    private GradesService gradesService;



    @GetMapping("/getWorks")
    public Result<List<WorksVO>> getWorks(@RequestParam Integer classId){
        return Result.success(gradesService.getWorks(classId));
    }

    /**
     * 查询该班级的成绩状态
     * @return
     */
    @GetMapping("/getWorkScores")
    public Result<List<WorkScoreVO>> getWorkScores(@RequestParam Integer classId, @RequestParam Integer workId){
        // 额外补充，根据这个classId和这个WorkId获取这个测试的结束时间
        LocalDateTime endTime = gradesService.getEndtime(classId,workId);
        // 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将 LocalDateTime 转换为字符串
        String dateTimeString = endTime.format(formatter);
        Result R = new Result();
        R.setCode(200);
        R.setMsg(dateTimeString);
        R.setData(gradesService.getWorkScores(classId,workId));
        return R;
    }


    /*
    成绩下载
     */
    @GetMapping(value = "/getScoreExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<Resource> downloadExcel(@RequestParam Integer classId, @RequestParam Integer workId) {
        List<WorkScoreVO> workScoreVOList = gradesService.getWorkScores(classId, workId);
        // 创建新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("WorkScores");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("姓名");
        headerRow.createCell(2).setCellValue("学号");
        headerRow.createCell(3).setCellValue("分数");

        // 填充数据行
        for (int i = 0; i < workScoreVOList.size(); i++) {
            WorkScoreVO workScoreVO = workScoreVOList.get(i);
            Row dataRow = sheet.createRow(i + 1); // 从第二行开始
            dataRow.createCell(0).setCellValue(i+1);
            dataRow.createCell(1).setCellValue(workScoreVO.getUsername());
            dataRow.createCell(2).setCellValue(workScoreVO.getStudentNumber());
            dataRow.createCell(3).setCellValue(workScoreVO.getScore()==null?0:workScoreVO.getScore());
        }

        // 写入到输出流中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如返回错误响应
        }

        // 创建ByteArrayResource对象
        Resource resource = new ByteArrayResource(outputStream.toByteArray());

        // 设置HTTP响应头
        String filename = "work_scores.xlsx";
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" + filename)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


    @GetMapping("/getTestTwoWorks")
    public Result<List<WorksVO>> getTestTwoWorks(@RequestParam Integer classId){
        List<WorksVO> works = gradesService.getWorks(classId);
        List<WorksVO> list = new ArrayList<>();
        for (WorksVO work : works) {
            if (work.getWorkType() == 2){
                list.add(work);
            }
        }
        return Result.success(list);
    }


    @GetMapping("/getUserId")
    public Result<List<Integer>> getUserId(@RequestParam Integer classId){
        return Result.success(gradesService.getUserIds(classId));
    }

    // 获取用户信息
    @GetMapping("/getUserMsg")
    public Result<UserMsgVO> getUserMsg(@RequestParam Integer userId){
        if (userId ==null){
            return Result.success(null);
        }
        return Result.success(gradesService.getUserMsg(userId));
    }

    // 获取题目信息
    @GetMapping("/getWorkMsg")
    public Result<WorkMsgVO> getWorkMsg(@RequestParam Integer workId){
        return Result.success(gradesService.getWorkmsg(workId));
    }

    // 获取题目学生答案数据
    @GetMapping("/getStudentAnswer")
    public Result<String> getStudentAnswer(@RequestParam Integer userId,@RequestParam Integer workId,@RequestParam Integer order) throws IOException {
        String address = gradesService.getAddress(userId,workId,order);
        String test = "该学生未提交";
        if (address == null|| address.equals("0")){
            return Result.error(test,201);
        }
        String code = readFileToString(address);
        return Result.success(code);
    }


    // 学生打分
    @PostMapping("/submitStudentScore")
    public Result<String> submitStudentScore(@RequestBody SubmitStudentScoreDTO submitStudentScoreDTO){
        Integer falt = gradesService.submitStudentScore(submitStudentScoreDTO);
        if (falt == 0){
            // 表示重复提交题目数据
            return Result.error("重复提交",602);
        }
        return Result.success(null);
    }

    // 修改学生分数
    @PostMapping("/updateStudentScore")
    public Result<String> updateStudentScore(@RequestBody SubmitStudentScoreDTO submitStudentScoreDTO){
        Integer falt =  gradesService.updateStudentScore(submitStudentScoreDTO);
        if (falt == 0){
            // 没有得分数据，不能修改
            return Result.error("请走提交按钮",602);
        }
        return Result.success(null);
    }

    // 获取学生test2得分情况
    @GetMapping("/getStudentScore")
    public Result<List<Double>> getStudentScore(@RequestParam Integer userId, Integer workId){
        return Result.success(gradesService.getStudentScore(userId,workId));
    }

    // 根据workId获取结束时间
    @GetMapping("getEndTime")
    public Result<String> getEndTime(@RequestParam Integer workId,@RequestParam Integer classId){
        // 额外补充，根据这个classId和这个WorkId获取这个测试的结束时间
        LocalDateTime endTime = gradesService.getEndtime(classId,workId);
        // 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将 LocalDateTime 转换为字符串
        String dateTimeString = endTime.format(formatter);
        if (endTime.isBefore(LocalDateTime.now())){
            // 表示这个结束时间已经结束了，即这个试卷已经不能继续提交
            return Result.success(dateTimeString);
        }
        return Result.error(dateTimeString,201);
    }


    // 读取文件
    public static String readFileToString(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        byte[] data = Files.readAllBytes(path);
        return new String(data, StandardCharsets.UTF_8);
    }

}
